var eventsMgr = require('eventsMgr');
var consts = require('consts');
var CellNode = require('CellNode');
let actions = require('actions');
cc.Class({
    extends: CellNode,

    properties: {
        // onDragStartId:'',
        // onDragSuccess:'',
        // onDragFail:'',
        // onDragWrong:'',
        // dragId:'',
        // targetNodes:[cc.Node],
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad () {

    },

    start () {
        this.orginX = this.node.x;
        this.orginY = this.node.y;

        this.offsetX = 0;
        this.offsetY = 0;
    },
    onDragStart(point){
        let self = this;
        if (!self.isMoveEnable){//不允许拖动
            return false;
        }else{
            self.orginX = self.node.x;
            self.orginY = self.node.y;
            self.offsetX = self.node.x-point.x;
            self.offsetY = self.node.y-point.y;
            eventsMgr.emit(consts.EVENTS.DRAG_START,{groupId:self.groupId,cellId:self.cellId});
            return true;
        }
    },
    onDragMove(point){
        let self = this;
        self.node.x = point.x+self.offsetX;
        self.node.y = point.y+self.offsetY;
    },

    onDragEnd(containers){
        let self = this;
        var point = this.node.getPosition();
        // let targets = self.targetNodes;
        let isDressToTarget = false;
        let container = undefined;
        let distance = 10000;
        for (let i=0;i<containers.length;i++){
            let containerTmp = containers[i];
            let node = containerTmp.node;
            let v2 = cc.v2(node.x,node.y);
            v2.subSelf(point);
            let tmpDis = v2.mag();
            if (tmpDis<distance){
                distance = tmpDis;
                container = containerTmp;
            }
        }
        if ( container && container.node){
            if (container.node.getBoundingBox().intersects(this.node.getBoundingBox())){
                if(self.node.name != "error"){
                    var result = container.addNode(self.node);
                }
                if (result){//添加成功!
                    eventsMgr.emit(consts.EVENTS.DRAG_SUCCESS,
                        {container:container,target:self});
                    isDressToTarget = true;
                }else{
                    eventsMgr.emit(consts.EVENTS.DRAG_WRONG,
                        {container:container,target:self});
                }
            }else{
                eventsMgr.emit(consts.EVENTS.DRAG_FAIL,
                    {container:container,target:self})
            }
        }
        if (!isDressToTarget){
            actions.moveTo(self.node,0.2,self.orginX,self.orginY);
        }
    },
    // update (dt) {},
});
